import 'dart:convert';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:azlistview/azlistview.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:hello_flutter/config/HttpUrlservices.dart';
import 'package:dio/dio.dart';
import 'package:hello_flutter/config/FontsConfig.dart';
import 'package:hello_flutter/pages/home/CitySearchPage.dart';
import 'package:hello_flutter/pages/home/HomePage.dart';
import 'package:hello_flutter/router/CustomAnimationRouter.dart';
import 'package:hello_flutter/utils/SharedPreferencesUtils.dart';

import 'CityModel.dart';

class CitySelect extends StatefulWidget {
  FluroRouter? router;
  String? cityName;
  CitySelect(FluroRouter? router, {Key? key, String? cityName}) {
    this.router = router;
    this.cityName = cityName;
  }

  @override
  _CitySelectState createState() => _CitySelectState(cityName: cityName);
}

class _CitySelectState extends State<CitySelect> {
  String? cityName;
  _CitySelectState({String? cityName}) {
    this.cityName = cityName;
  }

  List<CityModel> cityList = [];
  List<CityModel> _hotCityList = [];

  ///组头高度
  int _suspensionHeight = 36;

  ///cell高度
  int _itemHeight = 48;

  ///组头标签
  String _suspensionTag = " ";

  @override
  void initState() {
    super.initState();
    loadData();
  }

  //城市列表数据请求
  void loadData() async {
    super.initState();
    _hotCityList.add(CityModel(name: '北京市', tagIndex: '★'));
    _hotCityList.add(CityModel(name: '广州市', tagIndex: '★'));
    _hotCityList.add(CityModel(name: '成都市', tagIndex: '★'));
    _hotCityList.add(CityModel(name: '深圳市', tagIndex: '★'));
    _hotCityList.add(CityModel(name: '杭州市', tagIndex: '★'));
    _hotCityList.add(CityModel(name: '武汉市', tagIndex: '★'));
    cityList.addAll(_hotCityList);
    SuspensionUtil.setShowSuspensionStatus(cityList);

    Future.delayed(Duration(milliseconds: 500), () {
      loadData();
    });
  }

  ///城市接口请求
  Future userLogin() async {
    try {
      Response respose = await Dio().get(HttpUrlservices.getCityUrl);
      Map<String, dynamic> news = jsonDecode(respose.data);

      String dataValue = news['response']['data'].toString();

      if (!dataValue.contains('error')) {
        return news['response']['data'];
        // Navigator.of(context).pop();
      } else {
        List<String> datalist = dataValue.split('&');
      }
    } catch (e) {
      print(e);
    }
  }

  ///当前定位城市
  Widget _buildSusWidget(String susTag, int index) {
    susTag = (susTag == " " ? "开发中城市" : susTag);
    return Container(
      height: _suspensionHeight.toDouble(),
      padding: const EdgeInsets.only(left: 15.0),
      color: Color(0xfff3f4f5),
      alignment: Alignment.centerLeft,
      child: Text(
        '$susTag',
        softWrap: false,
        style: TextStyle(
          fontSize: 14.0,
          color: Color(0xff999999),
        ),
      ),
    );
  }

  ///热门城市
  Widget header() {
    return Container(
      color: Colors.white,
      height: 44.0,
      child: Row(
        children: <Widget>[
          Expanded(
              child: TextField(
                autofocus: false,
                decoration: InputDecoration(
                    contentPadding: EdgeInsets.only(left: 10, right: 10),
                    border: InputBorder.none,
                    labelStyle: TextStyle(fontSize: 14, color: Color(0xFF333333)),
                    hintText: '城市中文名或拼音',
                    hintStyle: TextStyle(fontSize: 14, color: Color(0xFFCCCCCC))),
              )),
          Container(
            width: 0.33,
            height: 14.0,
            color: Color(0xFFEFEFEF),
          ),
          InkWell(
            onTap: () {
              Navigator.pop(context);
            },
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: Text(
                "取消",
                style: TextStyle(color: Color(0xFF999999), fontSize: 14),
              ),
            ),
          )
        ],
      ),
    );
  }

  static void showSnackBar(BuildContext context, String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(msg),
        duration: Duration(seconds: 2),
      ),
    );
  }

  Widget getListItem(BuildContext context, CityModel model,
      {double susHeight = 40}) {
    return ListTile(
      title: Text(model.name),
      onTap: () {
        showSnackBar(context, 'onItemClick : ${model.name}');
      },
    );
  }

  static Widget getSusItem(BuildContext context, String tag,
      {double susHeight = 40}) {
    if (tag == '★') {
      tag = '★ 热门城市';
    }
    return Container(
      height: susHeight,
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.only(left: 16.0),
      color: Color(0xFFF3F4F5),
      alignment: Alignment.centerLeft,
      child: Text(
        '$tag',
        softWrap: false,
        style: TextStyle(
          fontSize: 14.0,
          color: Color(0xFF666666),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: SafeArea(
          child: Column(
            children: [
              header(),
              Expanded(
                child: Material(
                  color: Color(0x80000000),
                  child: Card(
                    clipBehavior: Clip.hardEdge,
                    margin: const EdgeInsets.only(left: 8, top: 8, right: 8),
                    shape: const RoundedRectangleBorder(
                      borderRadius: const BorderRadius.only(
                          topLeft: Radius.circular(4.0),
                          topRight: Radius.circular(4.0)),
                    ),
                    child: Column(
                      children: [
                        Container(
                          alignment: Alignment.centerLeft,
                          padding: const EdgeInsets.only(left: 15.0),
                          height: 50.0,
                          child: Text("当前城市: 成都市"),
                        ),
                        Expanded(
                          child: AzListView(
                            data: cityList,
                            itemCount: cityList.length,
                            itemBuilder: (BuildContext context, int index) {
                              CityModel model = cityList[index];
                              return getListItem(context, model);
                            },
                            padding: EdgeInsets.zero,
                            susItemBuilder: (BuildContext context, int index) {
                              CityModel model = cityList[index];
                              String tag = model.getSuspensionTag();
                              return getSusItem(context, tag);
                            },
                            indexBarData: ['★', ...kIndexBarData],
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ),
            ],
          )),
    );
  }

  ///头部组件
  Widget headerContent(context) {
    double screenWidth = MediaQuery.of(context).size.width;
    return Column(
      children: <Widget>[
        ///头部状态栏
        Container(
          padding: EdgeInsets.only(top: 0),
          // color: Colors.blue,
          height: 50,
          width: double.infinity,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                height: 40,
                width: 40,
                // color: Colors.red,
                child: IconButton(
                    icon: Image.asset('assets/images/zc_back.png'),
                    onPressed: () {
                      Navigator.of(context).push(CustomAnimationRouter(
                          HomePage(null, cityName: cityName)));
                      FocusScope.of(context).requestFocus(FocusNode());
                    },
                    color: Colors.transparent,
                    splashColor: Colors.transparent,
                    hoverColor: Colors.transparent),
              ),

              ///搜索框
              GestureDetector(
                  child: Container(
                    width: screenWidth - 60,
                    height: 32,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(32),
                        color: Color.fromRGBO(245, 245, 245, 1)),
                    child: Row(
                      children: <Widget>[
                        SizedBox(
                          width: 12,
                          height: 4,
                        ),
                        Image.asset('assets/images/Home_search.png',
                            fit: BoxFit.cover),
                        SizedBox(width: 8, height: 4),

                        ///输入框
                        Text(
                          '目的地',
                          style: TextStyle(
                            fontFamily: FontsConfig.$YAYAliFont,
                            fontSize: 14,
                            color: Color.fromRGBO(153, 153, 153, 1),
                          ),
                        ),
                      ],
                    ),
                  ),
                  onTap: () {
                    ///跳转到搜索页
                    Navigator.of(context).push(CustomAnimationRouter(
                        CitySearchPage(cityName: cityName)));
                  }),
            ],
          ),
        ),
      ],
    );
  }
}
